<?php

namespace app\common\controller;

use think\Controller;
use think\Request;
use think\Session;

class ApiBase extends Controller
{
    //状态参数
    const ERROR_DATA = -1; //失败错误
    const EMPTY_DATA = 0; //数据为空
    const SUCCESS_DATA = 1; //数据为空

    public function __construct()
    {
        Session::start();
        parent::__construct();
        $_acid=input('_acid');
        $_uniacid=input('_uniacid');
        if(!$_acid) return $this->ApiReture(self::ERROR_DATA,"网络错误，请重试");
        if(!$_uniacid) return $this->ApiReture(self::ERROR_DATA,"网络错误，请重试");
    }
    //响应结果
    public function  ApiReture($code,$msg,$data=[]){
        if(empty($data)){
            return json_encode(["code"=>$code,"msg"=>$msg],JSON_UNESCAPED_UNICODE);
        }else{
            return json_encode(["code"=>$code,"data"=>$data,"msg"=>$msg],JSON_UNESCAPED_UNICODE);
        }
    }
    /**
     * http请求get获取数据
     * @param $url
     * @return mixed
     */
    function  httpGet($url,$header=''){
        $ch=curl_init();
        if(substr($url,0,5)=='https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        }
        //设置选项，包括URL
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        //打印请求的header信息
        //curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        if($header)
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //执行并获取HTML文档内容
        $output=curl_exec($ch);

        //打印请求的header信息
        //$request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        //print_r($request_header);
        if($error=curl_error($ch)){
            die($error);
        }
        //释放curl句柄
        curl_close($ch);
        return $output;
    }

    /**
     * http请求post获取
     * @param $url
     * @param $params
     * @param string $header
     * @return mixed
     */
    function httpPost($url,$params,$header=''){
        $ch=curl_init();
        if(substr($url,0,5)=='https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        }
        //设置选项，包括URL
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch,CURLOPT_HEADER,0);
        if($header)
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //执行并获取HTML文档内容
        $output=curl_exec($ch);
        if($error=curl_error($ch)){
            die($error);
        }
        //释放curl句柄
        curl_close($ch);
        return $output;
    }
}
